<template>
  <!-- <div class="back_box" ref="back_box"> -->
    <div  class="cus-img drag_box" id="cusModal"    draggable="true"
        @dragstart="dragstart($event)"
        @dragend="dragend($event)"
        :style="`left:${elLeft}px;top:${elTop}px`">
    <div class="cus-img-mask"></div>

    <i class="el-icon-loading" v-if="loadingImg"></i>
    <!-- <el-image :src="url" style="width: 100%; height: 100%" v-else></el-image>    -->
  </div>
  <!-- </div> -->
</template>

<script>

export default {
  props: {
    fileId: {
      type: String,
      required: true,
    },
    parentClassName: {
      type: String,
      required: true,
    },
    applyId: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      initWidth: 0, // 父元素的宽-自适应值
      initHeight: 0, // 父元素的高-自适应值
      startclientX: 0, // 元素拖拽前距离浏览器的X轴位置
      startclientY: 0, //元素拖拽前距离浏览器的Y轴位置
      elLeft: 0, // 元素的左偏移量
      elTop: 0, // 元素的右偏移量


      width: 0,
      height: 0,
      scale: 0,
      url: "",
      resizeObserver: null,
      loadingImg: true,
    };
  },
  methods: {
  // 页面初始化
    initBodySize() {
      let dialogBody = document.getElementsByClassName(
            this.parentClassName
          );
      this.initWidth = dialogBody.clientWidth; // 拿到父元素宽
      // this.initHeight = this.initWidth * (1080 / 1920);
      this.initHeight = this.initWidth * ((1080 * 0.88) / (1920 - 1080 * 0.02)); // 根据宽计算高实现自适应
    },
    // 拖拽开始事件
    dragstart(e) {
      this.startclientX = e.clientX; // 记录拖拽元素初始位置
      this.startclientY = e.clientY;
    },
    // 拖拽完成事件
    dragend(e) {

      let x = e.clientX - this.startclientX; // 计算偏移量
      let y = e.clientY - this.startclientY;
      this.elLeft += x; // 实现拖拽元素随偏移量移动
      this.elTop += y;
    },

    async getPosition() {
      const res = await this.$axios.post("/graphql", {
        query: `{
                    similarityAnalysis  {
                                        analyze(attachmentId:"${this.fileId}",talentApplyId:"${this.applyId}") {
                                            value
                                            textInfo {
                                               content
                                              confidence
                                              positions{
                                                getX
                                                getY
                                                positionType
                                              }
                                            }

                                            }
                                        }
                         }`,
      });

      if (res.data.errors) {
        // this.$message.error("识别失败");
      } else {
        const areaRes = await this.$axios.post("/graphql", {
          query: `
                    {
                      ocrImageInfoQueryRepository {
                        findByAttachmentId(attachmentId: "${this.fileId}") {
                        id
                        attachmentId
                        width
                        height

                        result
                      }
                      }
                    }
                    `,
        });
        if (areaRes.data.errors) {
          // this.$message.error("图片宽高获取失败");
        } else {
          let areafindById =
            areaRes.data.data?.ocrImageInfoQueryRepository?.findByAttachmentId;
          if (!areafindById) {
            // this.$message.error("图片识别失败");

          }
          // 获取父元素
          let dialogBody = document.getElementsByClassName(
            this.parentClassName
          );
          let cusModal = dialogBody[0]?.children[0];
          if (!cusModal) {
            return;
          }
          const findById = res.data.data.similarityAnalysis?.analyze;
          if (!findById || findById?.length === 0) {
            this.loadingImg = false;
            return;
          }

          if (findById && areafindById) {
            // 图片的宽高
            this.width = areafindById.width;
            this.height = areafindById.height;
          }

          const modalBodyWidth = dialogBody[0]?.clientWidth;
          this.scale = modalBodyWidth / this.width;

          // 设置图片父元素的宽高
          cusModal.style.width = areafindById.width + "px";
          cusModal.style.height = areafindById.height + "px";

          dialogBody[0].style.height =
            areafindById.height * this.scale + 10 + "px";

          findById?.map((val) => {
            let textPositions = val.textInfo.positions;
            let div = document.createElement("div");
            div.innerHTML = val.value;
            const divWidth =
              val.textInfo.positions[1].getX - val.textInfo.positions[0].getX;
            const fontSize = divWidth / val.textInfo.content.length;
            // div.style.width = areafindById.width + "px";
            div.style.height = fontSize + "px";
            div.style.fontSize =
              this.calculatedFontSize(
                textPositions[0].getX,
                textPositions[1].getX,
                textPositions[2].getX,
                textPositions[3].getX,
                textPositions[0].getY,
                textPositions[1].getY,
                textPositions[2].getY,
                textPositions[3].getY,
                areafindById.width,
                areafindById.height,
                val.value
              ) + "px";

            div.style.top = val.textInfo.positions[0].getY - 20 + "px";
            div.style.left = val.textInfo.positions[0].getX + "px";
            div.className = "textInfo";
            cusModal.appendChild(div);
          });
          // 获取要缩放的文字元素
          const textElement = document.getElementsByClassName("textInfo");

          let arry = Array.from(textElement);
          arry?.forEach((element) => {
            element.addEventListener("mouseenter", function () {
              // 缩放文字
              element.style.transform = "scale(1.5)";
            });
          });
          arry?.forEach((element) => {
            element.addEventListener("mouseleave", function () {
              // 缩放文字
              element.style.transform = "scale(1)";
            });
          });
          cusModal.style.transform = `scale(${this.scale})`;
          this.loadingImg = false;

          // axios({
          //   method: "get",
          //   url: `/attachment?id=${this.fileId}`,
          //   responseType: "blob",
          // }).then((res) => {
          //   let blob = res.data;
          //   let reader = new FileReader();
          //   reader.readAsDataURL(blob);
          //   reader.onload = () => {
          //     this.url = reader.result;

          //   };
          //   reader.onerror = (e) => (this.loading = false);
          // });
        }
      }
      this.$emit("over");
    },

    eventHandler(e) {
      let dialogBody = document.getElementsByClassName(this.parentClassName);
      let cusModal = dialogBody[0].children[0];

      if (dialogBody) {
        const modalBodyWidth = dialogBody[0].clientWidth;
        this.scale = (modalBodyWidth - 50) / this.width;

        dialogBody[0].style.height = this.height * this.scale + 100 + "px";
        cusModal.style.transform = `scale(${this.scale})`;
      }
    },
    calculatedFontSize(x1, x2, x3, x4, y1, y2, y3, y4, width, height, text) {
      const textWidth = Math.max(x1, x2, x3, x4) - Math.min(x1, x2, x3, x4);
      const textHeight = Math.max(y1, y2, y3, y4) - Math.min(y1, y2, y3, y4);
      const widthRatio = textWidth / text?.length;
      const heightRatio = textHeight;
      const fontSize = Math.min(widthRatio, heightRatio);
      return heightRatio;
    },
  },

  mounted() {

    window.addEventListener("resize", this.eventHandler);
    this.$nextTick(async () => {
      setTimeout(() => {
        this.getPosition();
    this.initBodySize();
      }, 2000);
    });
  },
  destroyed() {
    window.removeEventListener("resize", this.eventHandler);
  },
};
</script>

<style lang="scss">
#cusModal {
  cursor: move;
  transform-origin: top left;
  position: relative;
  text-align: left;

  .textInfo {
    position: absolute;
    z-index: 99;
    color: blue;
    height: auto;
  }

  .hiden-img {
    overflow: hidden;
    opacity: 0;
  }
}
.back_box {
  background: #ccc;
  width: 50vw;
  height: 50vh;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -30%);
}

.drag_box {
  width: 100px;
  height: 100px;
  // background: skyblue;
  position: absolute;
  z-index: 10;
  user-select: none; /* 不可选中,为了拖拽时不让文字高亮 */
}


</style>
